﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Text;
//needs a ref. to System.Web.Extensions asm.
using System.Web.Script.Serialization;
using System.IO;
using BloggerAutoPosterService.Engine.Utils;

namespace BloggerAutoPosterService.Engine.Core
{
    [DebuggerDisplay("{DateTime}-{Title}-{Comment}-{Url}")]
    public class GooglePlusItem
    {
        #region Properties (4)

        public string Comment { set; get; }

        public DateTime DateTime { set; get; }

        public string Title { set; get; }

        public string Url { set; get; }

        #endregion Properties
    }

    public static class Utils
    {
        #region Methods (2)

        // Public Methods (2) 

        public static DateTime ConvertFromUnixTimestamp(this long data)
        {
            return new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(data);
        }

        public static string ToSafeString(this object data)
        {
            return data == null ? string.Empty : data.ToString();
        }

        #endregion Methods
    }

    public static class GooglePlusJsonParser
    {
        public static IList<GooglePlusItem> GetMyPublicItemsList(string userId)
        {
            var url = string.Format("https://plus.google.com/_/stream/getactivities/?&sp=[1,2,\"{0}\",null,null,null,null,\"social.google.com\",[]]", userId.Trim());
            var jsonData = new WebClient { Encoding = Encoding.UTF8 }.DownloadString(url);
            if (string.IsNullOrWhiteSpace(jsonData))
                throw new InvalidOperationException("Couldn't receive Google+ data.");

            return ParsePublicData(jsonData);
        }

        public static IList<GooglePlusItem> ParsePublicData(string jsonData)
        {
            if (!CheckPermission.HasWritePermission("lastJson.txt")) return new List<GooglePlusItem>();
            File.WriteAllText("lastJson.txt", jsonData);
            jsonData = removeRedundantData(jsonData);
            var posts = parseJson(jsonData);
            return createItemsList(posts);
        }

        private static IList<GooglePlusItem> createItemsList(object[] posts)
        {
            var result = new List<GooglePlusItem>();
            if (posts == null) return result;

            foreach (object[] post in posts)
            {
                var data = (object[])post[66];
                if (data.Length == 0)
                {
                    result.Add(new GooglePlusItem
                    {
                        DateTime = (((Int64)post[5]) / 1000).ConvertFromUnixTimestamp(),
                        Title = post[4].ToSafeString(),
                        Url = post[1].ToSafeString(),
                        Comment = post[20].ToSafeString()
                    });
                }
                else
                {
                    var items = (object[])(data)[0];
                    result.Add(new GooglePlusItem
                    {
                        DateTime = (((Int64)post[5]) / 1000).ConvertFromUnixTimestamp(),
                        Title = items[3].ToSafeString(),
                        Url = items[1].ToSafeString(),
                        Comment = post[20].ToSafeString()
                    });
                }
            }
            return result;
        }

        private static object[] parseJson(string jsonData)
        {
            var jsonObject = new JavaScriptSerializer().Deserialize<object[]>(jsonData);
            if (jsonObject == null) return null;
            var posts = (object[])(((object[])jsonObject[1])[0]);
            return posts;
        }

        private static string removeRedundantData(string jsonData)
        {
            if (jsonData.Contains(")]}'\n\n[")) //as of 3.12.2011
            {
                jsonData = jsonData.Replace(")]}'\n\n[", string.Empty).Trim();
                jsonData = jsonData.Remove(jsonData.Length - 1); //remove last ']'
            }
            return jsonData.Replace(")]}'", string.Empty)
                           .Replace("[,", "[\"\",")
                           .Replace(",,", ",\"\",")
                           .Replace(",,", ",\"\",");
        }
    }
}
